/**
 * 全局用户状态管理
 * 统一管理用户登录状态、用户信息等
 */

class UserStateManager {
	constructor() {
		this.userInfo = {
			userId: '',
			nickname: '',
			avatar: '',
			gender: 0,
			birthday: '',
			region: '',
			bio: '',
			phone: '',
			wechatOpenId: '',
			preferredMethod: 'time',
			saveRecords: true,
			enableNotification: true
		}
		this.isLoggedIn = false
		this.loginType = '' // 'wechat', 'phone', 'guest'
		this.observers = [] // 观察者列表
		
		this.init()
	}
	
	/**
	 * 初始化状态管理器
	 */
	init() {
		// 从本地存储恢复用户状态
		this.loadFromStorage()
	}
	
	/**
	 * 从本地存储加载用户信息
	 */
	loadFromStorage() {
		try {
			// 加载登录状态
			uni.getStorageSync('login_status')
			const loginStatus = uni.getStorageSync('login_status')
			if (loginStatus) {
				this.isLoggedIn = loginStatus.isLoggedIn || false
				this.loginType = loginStatus.loginType || ''
			}
			
			// 加载用户信息
			const userInfo = uni.getStorageSync('user_info')
			if (userInfo) {
				this.userInfo = { ...this.userInfo, ...userInfo }
			}
		} catch (error) {
			console.error('加载用户状态失败:', error)
		}
	}
	
	/**
	 * 保存状态到本地存储
	 */
	saveToStorage() {
		try {
			uni.setStorageSync('login_status', {
				isLoggedIn: this.isLoggedIn,
				loginType: this.loginType
			})
			
			uni.setStorageSync('user_info', this.userInfo)
		} catch (error) {
			console.error('保存用户状态失败:', error)
		}
	}
	
	/**
	 * 用户登录
	 * @param {Object} loginResult 登录结果
	 * @param {string} type 登录类型
	 */
	login(loginResult, type = 'wechat') {
		this.isLoggedIn = true
		this.loginType = type
		
		// 更新用户信息
		if (loginResult.userInfo) {
			this.updateUserInfo(loginResult.userInfo)
		}
		
		// 保存到本地存储
		this.saveToStorage()
		
		// 通知观察者
		this.notifyObservers('login', {
			isLoggedIn: this.isLoggedIn,
			loginType: this.loginType,
			userInfo: this.userInfo
		})
	}
	
	/**
	 * 用户登出
	 */
	logout() {
		this.isLoggedIn = false
		this.loginType = ''
		this.userInfo = {
			userId: '',
			nickname: '',
			avatar: '',
			gender: 0,
			birthday: '',
			region: '',
			bio: '',
			phone: '',
			wechatOpenId: '',
			preferredMethod: 'time',
			saveRecords: true,
			enableNotification: true
		}
		
		// 清除本地存储
		try {
			uni.removeStorageSync('login_status')
			uni.removeStorageSync('user_info')
			uni.removeStorageSync('user_token')
		} catch (error) {
			console.error('清除用户数据失败:', error)
		}
		
		// 通知观察者
		this.notifyObservers('logout', {
			isLoggedIn: this.isLoggedIn
		})
	}
	
	/**
	 * 更新用户信息
	 * @param {Object} newInfo 新的用户信息
	 */
	updateUserInfo(newInfo) {
		this.userInfo = { ...this.userInfo, ...newInfo }
		this.saveToStorage()
		
		// 通知观察者
		this.notifyObservers('updateUserInfo', {
			userInfo: this.userInfo
		})
	}
	
	/**
	 * 获取当前用户状态
	 */
	getCurrentState() {
		return {
			isLoggedIn: this.isLoggedIn,
			loginType: this.loginType,
			userInfo: { ...this.userInfo }
		}
	}
	
	/**
	 * 检查是否已登录
	 */
	checkLoginStatus() {
		return {
			isLoggedIn: this.isLoggedIn,
			loginType: this.loginType,
			userInfo: this.isLoggedIn ? { ...this.userInfo } : null
		}
	}
	
	/**
	 * 添加状态观察者
	 * @param {Function} observer 观察者函数
	 */
	addObserver(observer) {
		if (typeof observer === 'function') {
			this.observers.push(observer)
		}
	}
	
	/**
	 * 移除状态观察者
	 * @param {Function} observer 观察者函数
	 */
	removeObserver(observer) {
		const index = this.observers.indexOf(observer)
		if (index > -1) {
			this.observers.splice(index, 1)
		}
	}
	
	/**
	 * 通知所有观察者
	 * @param {string} type 事件类型
	 * @param {Object} data 事件数据
	 */
	notifyObservers(type, data) {
		this.observers.forEach(observer => {
			try {
				observer(type, data)
			} catch (error) {
				console.error('通知观察者失败:', error)
			}
		})
	}
	
	/**
	 * 获取用户显示名称
	 */
	getDisplayName() {
		if (this.isLoggedIn && this.userInfo.nickname) {
			return this.userInfo.nickname
		}
		return this.isLoggedIn ? '易学爱好者' : '点击登录'
	}
	
	/**
	 * 获取用户显示描述
	 */
	getDisplayDesc() {
		if (this.isLoggedIn && this.userInfo.bio) {
			return this.userInfo.bio
		}
		return this.isLoggedIn ? '探索传统智慧的奥秘' : '登录后享受完整功能'
	}
	
	/**
	 * 检查用户权限
	 * @param {string} action 操作类型
	 */
	checkPermission(action) {
		switch (action) {
			case 'saveRecord':
				return this.isLoggedIn && this.userInfo.saveRecords
			case 'viewRecords':
			case 'viewFavorites':
			case 'editProfile':
				return this.isLoggedIn
			default:
				return true
		}
	}
	
	/**
	 * 获取工具自动填写信息
	 * 返回用于工具页面自动填写的用户信息
	 */
	getAutoFillInfo() {
		if (!this.isLoggedIn) {
			return null
		}
		
		return {
			name: this.userInfo.nickname || '',
			gender: this.userInfo.gender === 1 ? 'male' : (this.userInfo.gender === 2 ? 'female' : ''),
			birthday: this.userInfo.birthday || '',
			region: this.userInfo.region || '',
			phone: this.userInfo.phone || ''
		}
	}
	
	/**
	 * 检查用户信息完整度
	 * 返回缺失的必要信息列表
	 */
	checkUserInfoCompleteness() {
		if (!this.isLoggedIn) {
			return ['请先登录']
		}
		
		const missing = []
		
		if (!this.userInfo.nickname) {
			missing.push('姓名')
		}
		
		if (!this.userInfo.gender || this.userInfo.gender === 0) {
			missing.push('性别')
		}
		
		if (!this.userInfo.birthday) {
			missing.push('生日')
		}
		
		return missing
	}
	
	/**
	 * 提示用户完善信息
	 */
	promptCompleteInfo() {
		const missing = this.checkUserInfoCompleteness()
		
		if (missing.length === 0) {
			return false
		}
		
		if (missing.includes('请先登录')) {
			uni.showModal({
				title: '提示',
				content: '请先登录以享受自动填写功能',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
				}
			})
			return true
		}
		
		uni.showModal({
			title: '完善个人信息',
			content: `为了更好的占卜体验，建议完善以下信息：${missing.join('、')}`,
			confirmText: '去完善',
			success: (res) => {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/user-info/user-info'
					})
				}
			}
		})
		
		return true
	}
	async generateUserStats() {
		if (!this.isLoggedIn) {
			return {
				totalDivinations: 0,
				totalDays: 0,
				favoriteHexagram: '乾为天'
			}
		}
		
		try {
			// 从本地存储获取占卜记录
			const records = uni.getStorageSync('divination_records') || []
			
			const stats = {
				totalDivinations: records.length,
				totalDays: 0,
				favoriteHexagram: '乾为天'
			}
			
			// 计算使用天数
			if (records.length > 0) {
				const firstRecord = records[records.length - 1]
				const lastRecord = records[0]
				const firstDate = new Date(firstRecord.timestamp)
				const lastDate = new Date(lastRecord.timestamp)
				const diffTime = Math.abs(lastDate - firstDate)
				stats.totalDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
			}
			
			// 计算最常见卦象
			if (records.length > 0) {
				const hexagramCount = {}
				records.forEach(record => {
					const name = record.hexagram.name
					hexagramCount[name] = (hexagramCount[name] || 0) + 1
				})
				
				let maxCount = 0
				let mostCommon = '乾为天'
				for (const [name, count] of Object.entries(hexagramCount)) {
					if (count > maxCount) {
						maxCount = count
						mostCommon = name
					}
				}
				stats.favoriteHexagram = mostCommon
			}
			
			return stats
		} catch (error) {
			console.error('生成用户统计失败:', error)
			return {
				totalDivinations: 0,
				totalDays: 0,
				favoriteHexagram: '乾为天'
			}
		}
	}
}

// 创建全局实例
const userStateManager = new UserStateManager()

// 导出
export { userStateManager as UserStateManager }
export default userStateManager